﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using ESOL.Common.Entity;
using ESOL.Common;
using ESOL.Business.Mst;
using ESOL.Business.Sales;

namespace ESOL.WinUI.Sales
{
    public partial class frmMaintainReturnOrder : BaseForm.frmBaseDialogyBusinessForm
    {
        #region Variable
        public SalesReturnOrderEntity selectedReturnOrder { get; set; }
        private DataRow  mselectedRow;
        private List<SalesReturnItemEntity> deleteSalesReturnItems = new List<SalesReturnItemEntity>();
        private List<SalesReturnItemEntity> salesReturnItems = new List<SalesReturnItemEntity>();
        private List<SalesProdPlanApplicationItemEntity> selectedProdAppItems = new List<SalesProdPlanApplicationItemEntity>();
        #endregion

        #region Constructor
        public frmMaintainReturnOrder()
        {
            InitializeComponent();
            if (selectedReturnOrder == null)
            {
                selectedReturnOrder = new SalesReturnOrderEntity();
                selectedReturnOrder.ApplicationId = Guid.NewGuid().ToString();
            }
        }
        public frmMaintainReturnOrder(List<SalesProdPlanApplicationItemEntity> list, MstCustomerEntity customer)
        {
            InitializeComponent();
            if (selectedReturnOrder == null)
            {
                selectedReturnOrder = new SalesReturnOrderEntity();
                selectedReturnOrder.ApplicationId = Guid.NewGuid().ToString();
            }
            selectedProdAppItems = list;
            txtCustomer.Tag = customer;
            txtCustomer.Text = customer.CustomerName;
            SalesProdPlanApplicationEntity entity = SalesProdPlanApplicationBs.GetSalesProdPlanApplicationByID(list[0].ApplicationId);
            txtApplicationCode.Text = entity.ApplicationCode;
            txtApplicationCode.Tag = entity;
            
        }
        #endregion

        #region Functions
        private void BindCombobox()
        {
            UICommon.UICommonFunctions.BindComboboxByCommonItem(cmbStatus, "SRO", true);
            UICommon.UICommonFunctions.BindGridComboboxByCommonItem(repositoryItemGridLookUpEdit1, "UNIT", true);
            cmbStatus.SelectedValue = "SRO01";
        }
        private void SetField()
        {
            if (selectedReturnOrder == null ||selectedReturnOrder.Id=="")
            {

                BindDataGridDetail();
                return;
            }

            BindDataGridDetail();
            txtReturnOrderCode.Text = selectedReturnOrder.OrderCode;
            txtApplicationCode.Text = selectedReturnOrder.ApplicationCode;
            dtpOrderDate.EditValue = selectedReturnOrder.OrderDate;
            SalesProdPlanApplicationEntity prodApp=SalesProdPlanApplicationBs.GetSalesProdPlanApplicationByID(selectedReturnOrder.ApplicationId);
            if (prodApp != null)
            {
                txtApplicationCode.Tag = prodApp;
            }
            MstCustomerEntity entity = MstCustomerBs.GetMstCustomerByID(selectedReturnOrder.CustomerId);
            if (entity != null)
            {
                txtCustomer.Text = entity.CustomerName;
                txtCustomer.Tag = entity;
            }
            cmbStatus.SelectedValue = selectedReturnOrder.Status;
            txtRemark.Text = selectedReturnOrder.Remark;

            UICommon.UICommonFunctions.SetTextBoxPersonName(txtCreatedBy, selectedReturnOrder.CreatedBy);
            UICommon.UICommonFunctions.SetTextBoxPersonName(txtModifiedBy, selectedReturnOrder.ModifiedBy);
            UICommon.UICommonFunctions.SetTextBoxPersonName(txtApprovedBy, selectedReturnOrder.ApprovedBy);
            UICommon.UICommonFunctions.SetTextBoxDate(txtCreatedDate, selectedReturnOrder.Created, "yyyy-MM-dd hh:mm:ss");
            UICommon.UICommonFunctions.SetTextBoxDate(txtModifiedDate, selectedReturnOrder.Modified, "yyyy-MM-dd hh:mm:ss");
            UICommon.UICommonFunctions.SetTextBoxDate(txtApprovedDate, selectedReturnOrder.Approved, "yyyy-MM-dd hh:mm:ss");


           
        }
        private void SetEntity()
        {
            if (selectedReturnOrder.Id == null||selectedReturnOrder.Id.ToString().Trim()=="")
            {
                selectedReturnOrder.Id = Guid.NewGuid().ToString();
            }
            if (txtApplicationCode.Tag != null&&txtApplicationCode.Tag.GetType()==typeof(SalesProdPlanApplicationEntity))
            {
                selectedReturnOrder.ApplicationCode = txtApplicationCode.Text;
                selectedReturnOrder.ApplicationId = ((SalesProdPlanApplicationEntity)txtApplicationCode.Tag).ApplicationId;
            }
            if (txtCustomer.Text != null && txtCustomer.Tag.GetType() == typeof(MstCustomerEntity))
            {
                selectedReturnOrder.CustomerId = ((MstCustomerEntity)txtCustomer.Tag).CustomerId;
            }
            if (dtpOrderDate != null)
            {
                selectedReturnOrder.OrderDate = (DateTime)dtpOrderDate.EditValue;
            }
            selectedReturnOrder.Remark = txtRemark.Text;
            if (ThisActionType == ActionType.New)
            {
                selectedReturnOrder.Status = "SRO01";
                selectedReturnOrder.CreatedBy = CommonParameter.CurrentUser.PersonId;
                selectedReturnOrder.Created = DateTime.Now;
                selectedReturnOrder.ModifiedBy = CommonParameter.CurrentUser.PersonId;
                selectedReturnOrder.Modified = DateTime.Now;
            }
            if (ThisActionType == ActionType.Modify)
            {
                selectedReturnOrder.Status = "SRO02";
                selectedReturnOrder.ModifiedBy = CommonParameter.CurrentUser.PersonId;
                selectedReturnOrder.Modified = DateTime.Now;
            }
        }
        private void SetDataRowByApplicationItem(DataRow dr, SalesProdPlanApplicationItemEntity entity)
        {
            //dr["CONTACT_ID"] = entity.ContactId;
            dr["ID"] = Guid.NewGuid().ToString();
            dr["SALES_RETURN_ORDER_ID"] = selectedReturnOrder.Id;
            dr["SALES_PROD_PLAN_APPLICATION_ITEM_ID"] = entity.ApplicationItemId;
            dr["PRICE"] = decimal.Round(entity.Price, 2);
            dr["RETURN_QTY"] = entity.Qty;
            dr["TOTAL_AMOUNT"] = decimal.Round(entity.Price * entity.Qty, 2);
            dr["PRODUCT_SPEC_OUT"] = entity.ProductSpecOut;

            MstProductEntity product = MstProductBs.GetMstProductByApplicationItemID(entity.ApplicationItemId);
            if (product != null)
            {
                dr["PRODUCT_ID"] = product.ProductId;
                dr["PRODUCT_CODE"] = product.ProductCode;
                dr["PRODUCT_NAME"] = product.ProductName;
                dr["PRODUCT_SPEC_IN"] = product.ProductSpecIn;
                dr["MATERIAL"] = product.Material;
                dr["UNIT"] = product.Unit;
            }

        }
        private void SetGridViewByApplicationItems()
        {
            if (selectedProdAppItems == null)
            {
                return;
            }
            if (selectedReturnOrder !=null&&!string.IsNullOrEmpty(selectedReturnOrder.OrderCode))
            {
                return;
            }
            DataTable dt = SalesReturnItemBs.GetSalesReturnItemsByReturnOrderId("").Tables[0];
            dt.Columns.Add("TOTAL_AMOUNT");
            foreach (SalesProdPlanApplicationItemEntity entity in selectedProdAppItems)
            {
                DataRow dr = dt.NewRow();
                SetDataRowByApplicationItem(dr, entity);
                dt.Rows.Add(dr);
            }
            gvMain.DataSource = dt;
        }
        private void BindDataGridDetail()
        {
            if (selectedReturnOrder == null||selectedReturnOrder.Id=="")
            {
                gvMain.DataSource = null;
                return;
            }
            DataSet ds = SalesReturnItemBs.GetSalesReturnItemsByReturnOrderId(selectedReturnOrder.Id);
            if (ds.Tables[0] == null || ds.Tables[0].Rows.Count == 0)
            {
                gvMain.DataSource = null;
                return;
            }
            gvMain.DataSource = ds.Tables[0];
            deleteSalesReturnItems = new List<SalesReturnItemEntity>();
        }
        private bool CheckData()
        {
            if (string.IsNullOrEmpty(txtApplicationCode.Text))
            {
                MessageBox.Show("申请单号不能为空", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return false;
            }
            if (string.IsNullOrEmpty(txtCustomer.Text))
            {
                MessageBox.Show("客户不能为空！", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return false;
            }
            if (dtpOrderDate.EditValue == null)
            {
                MessageBox.Show("退货时间不能为空！", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return false;
            }
            return true;
        }
        private bool Save()
        {
            try
            {
                if (CheckData() == false)
                {
                    return false;
                }
                if (ThisActionType == ActionType.New)
                {
                    SetEntity();
                    DataTable dt = gvMain.DataSource as DataTable;
                    string msg="";
                    bool isSuccessful = SalesReturnOrderBs.UpdateReturn(selectedReturnOrder, dt, true, deleteSalesReturnItems, msg);
                    if (!isSuccessful)
                    {
                        MessageBox.Show("新增失败！", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        return false;
                    }
                }
                else if (ThisActionType == ActionType.Modify)
                {
                    SetEntity();
                    DataTable dt = gvMain.DataSource as DataTable;
                    string msg = "";
                    bool isSuccessful = SalesReturnOrderBs.UpdateReturn(selectedReturnOrder, dt, false, deleteSalesReturnItems, msg);
                    if (!isSuccessful)
                    {
                        MessageBox.Show("修改失败！", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        return false;
                    }
                }
                else if (ThisActionType == ActionType.Approve)
                {
                    SetEntity();
                    selectedReturnOrder.ApprovedBy = CommonParameter.CurrentUser.PersonId;
                    selectedReturnOrder.Approved = DateTime.Now;
                    bool isSuccessful = SalesReturnOrderBs.UpdateSalesReturnOrder(selectedReturnOrder);
                    if (!isSuccessful)
                    {
                        MessageBox.Show("审核失败！", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        return false;
                    }
                }

                return true;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return false;
            }
            
        }

        #endregion

        private void frmMaintainReturnOrder_Load(object sender, EventArgs e)
        {
            BindCombobox();
            SetField();
            SetGridViewByApplicationItems();
        }
        protected override void Click_Save()
        {
            if (Save())
            {
                this.DialogResult = DialogResult.OK;
            }
        }
        protected override void Click_Approve()
        {
            if (selectedReturnOrder == null)
            {
                return;
            }
            selectedReturnOrder.Status = "SRO03";
            if (Save())
            {
                this.DialogResult = DialogResult.OK;
            }
        }
        protected override void Click_Reject()
        {
            if (selectedReturnOrder == null)
            {
                return;
            }
            selectedReturnOrder.Status = "SRO04";
            if (Save())
            {
                this.DialogResult = DialogResult.OK;
            }
        }

        private void txtApplicationCode_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            frmMaintainProductPlanApplicationQuery frm = new frmMaintainProductPlanApplicationQuery();
            DialogResult dr = frm.ShowDialog();
            if (dr == DialogResult.OK)
            {
                txtApplicationCode.Text = frm.SelectedProdPlanApplication.ApplicationCode;
                txtApplicationCode.Tag = frm.SelectedProdPlanApplication;
                MstCustomerEntity entity = MstCustomerBs.GetMstCustomerByID(frm.SelectedProdPlanApplication.CustomerId);
                if (entity != null)
                {
                    txtCustomer.Text = entity.CustomerName;
                    txtCustomer.Tag = entity;
                }
                selectedProdAppItems = SalesProdPlanApplicationItemBs.GetProdPlanApplicationItemByAppID(frm.SelectedProdPlanApplication.ApplicationId);
                SetGridViewByApplicationItems();
            }
            else
            {
                txtApplicationCode.Text = "";
                txtApplicationCode.Tag = null;
            }
        }

        private void txtCustomer_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            frmMaintainCustomerQuery frm = new frmMaintainCustomerQuery();
            DialogResult dr = frm.ShowDialog();
            if (dr == DialogResult.OK)
            {
                txtCustomer.Text = frm.SelectedCustomer.CustomerName;
                txtCustomer.Tag = frm.SelectedCustomer;
            }
            else
            {
                txtCustomer.Text = "";
                txtCustomer.Tag = null;
            }
        }

        private void cmsDelete_Click(object sender, EventArgs e)
        {
            if (mselectedRow == null)
            {
                return;
            }
            DataTable dt = gvMain.DataSource as DataTable;
            if (mselectedRow.RowState != DataRowState.Added && ThisActionType!=ActionType.New)
            {
                SalesReturnItemEntity entity = new SalesReturnItemEntity(mselectedRow);
                deleteSalesReturnItems.Add(entity);
            }
            dt.Rows.Remove(mselectedRow);
            dt.AcceptChanges();
        }

        private void gridView1_RowClick(object sender, DevExpress.XtraGrid.Views.Grid.RowClickEventArgs e)
        {
            mselectedRow = gridView1.GetDataRow(e.RowHandle);
        }



    }

}